class WebSocketService {
  constructor() {
    this.socket = null
    this.callbacks = {}
  }

  connect(url) {
    this.socket = new WebSocket(url)

    this.socket.onmessage = (event) => {
      const data = JSON.parse(event.data)
      Object.values(this.callbacks).forEach(cb => cb(data))
    }

    this.socket.onclose = () => {
      setTimeout(() => this.connect(url), 5000)
    }
  }

  subscribe(key, callback) {
    this.callbacks[key] = callback
  }

  unsubscribe(key) {
    delete this.callbacks[key]
  }
}

export const ws = new WebSocketService() 